﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LitJson;
using SufeiUtil;

namespace Live
{
    public class DouyuTv : BasePlatform
    {
        private readonly DouyuTvRoom room = new DouyuTvRoom();

        public override bool Init(string url)
        {
            //房间信息
            string html = ReqRoomInfo(GetRoomId(url));

            JsonData data = JsonMapper.ToObject(html);
            int errno = int.Parse(data["error"].ToString());
            if (errno == 0)
            {
                room.ID = data["data"]["room_id"].ToString();
                room.Name = data["data"]["room_name"].ToString();
                room.UserName = data["data"]["owner_name"].ToString();
                room.UserAvatar = data["data"]["avatar"].ToString();

                html = ReqRoomHls(GetRoomId(url));
                data = JsonMapper.ToObject(html);
                errno = int.Parse(data["error"].ToString());
                if (errno == 0)
                {
                    string hls = data["data"]["hls_url"].ToString();
                    room.Hls = hls.Replace("\\", "");
                    return true;
                }
            }
            else
            {
                return false;
            }
            return false;
        }

        private string ReqRoomHls(string roomId)
        {
            string url = String.Format("https://m.douyu.com/html5/live?roomId={0}", roomId);

            HttpItem item = new HttpItem();
            item.Method = "GET";
            item.URL = url;
            item.Host = "m.douyu.com";
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            item.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

            return mHelper.GetHtml(item).Html;
        }

        protected  override string ReqRoomInfo(string roomId)
        {
            string url = String.Format("http://open.douyucdn.cn/api/RoomApi/room/{0}", roomId);

            HttpItem item = new HttpItem();
            item.Method = "GET";
            item.URL = url;
            item.Host = "open.douyucdn.cn";
            item.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            item.UserAgent =
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

            return mHelper.GetHtml(item).Html;
        }

        public override bool IsLive()
        {
            throw new NotImplementedException();
        }

        public override Room GetRoomInfo()
        {
            return room;
        }

        public override string GetLivePlayUrl()
        {
            return room.Hls;
        }
    }
}